package com.zkingsoft.rhi.handler;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;
import java.net.BindException;

/**
 * @author xieguo
 * @since 2020/11/4 11:22
 */


@Slf4j
@ControllerAdvice
@RestController
public class CommonExceptionHandler {


    /**
     * Java一般异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public JSONObject exceptionHandler(Exception e){
        e.printStackTrace();
        if(e instanceof BindException){
            int index = e.getMessage().lastIndexOf("[");
            return Result.setResultByCodeAndMsg(2, index!= -1?e.getMessage().substring(index + 1,e.getMessage().length()-1).trim():e.getMessage());
        }
        return Result.defeatedResultByMsg(e.toString());
    }

    /**
     * @author xieguo
     * 处理字段过长异常
     * @param e
     * @return com.alibaba.fastjson.JSONObject
     * @date 2020/11/13 9:51
     */
    @ExceptionHandler(DataIntegrityViolationException.class)
    @ResponseBody
    public JSONObject dataIntegrityViolationExceptionHandler(DataIntegrityViolationException e){
        return Result.setResultByCodeAndMsg(Result.STATUS_FAIL,"字段过长，请录入正常字段");
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public JSONObject httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e){
        return Result.setResultByCodeAndMsg(Result.STATUS_FAIL,"请求方式有问题");
    }
    
}